<?php

namespace App\Observers\Train;

use App\Models\Train\Stations\Repositories\Interfaces\StationRepositoryInterface;
use App\Models\Train\Stations\Repositories\StationRepository;
use App\Models\Train\Trains\Train;
use Illuminate\Support\Facades\Cache;
use function config;

class TrainsObserver
{
    public function creating(Train $train)
    {
        $this->station_name($train);
    }

    private function station_name(Train $train)
    {
        /**
         * @var StationRepository $stationRepo
         */
        $stationRepo = app(StationRepositoryInterface::class);
        if (!$train->start_station) {
            $start_station        = $stationRepo->findOneByCode($train->start_station_code);
            $train->start_station = $start_station?->getStationName() ?: '';
        }
        if (!$train->end_station) {
            $end_station        = $stationRepo->findOneByCode($train->end_station_code);
            $train->end_station = $end_station?->getStationName() ?: '';
        }
    }

    public function updating(Train $train)
    {
        $this->station_name($train);
    }

    public function saving(Train $train)
    {
        $this->station_name($train);
    }

    /**
     * Handle the User "created" event.
     *
     * @param Train $train
     * @return void
     */
    public function created(Train $train)
    {
        $cache_key = "Train:info:{$train->train_code}";
        Cache::put($cache_key, $train, config('trip.ttl.day'));
    }

    /**
     * Handle the User "updated" event.
     *
     * @param Train $train
     * @return void
     */
    public function updated(Train $train)
    {
        $cache_key = "Train:info:{$train->train_code}";
        Cache::put($cache_key, $train, config('trip.ttl.day'));
    }

    public function saved(Train $train)
    {
        $cache_key = "Train:info:{$train->train_code}";
        Cache::put($cache_key, $train, config('trip.ttl.day'));
    }
}
